package com.water.wfo.component.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * packageName com.water.wfo.component.util
 *
 * @author junhuili
 * @version JDK 8
 * @date 2024/5/28
 * @description TODO
 */
@Slf4j
public class MD5Util {
    public static final int LENGTH = 16;
    public static final int CHAR_LENGTH = 32;
    public static final int FOUR_BIT = 4;

    /**
     * md5加密
     *
     * @param s
     * @return
     */
    public static String getMD5Encoding(String s) {

        String output = null;

        try {
            byte[] input = s.getBytes("UTF-8");

            // 声明16进制字母
            char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'A', 'B', 'C', 'D', 'E', 'F'};
            // 获得一个MD5摘要算法的对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input);
            // 获得MD5的摘要结果
            byte[] tmp = md.digest();
            char[] str = new char[CHAR_LENGTH];
            byte b = 0;
            for (int i = 0; i < LENGTH; i++) {
                b = tmp[i];
                // 取每一个字节的低四位换成16进制字母
                str[2 * i] = hexChar[b >>> FOUR_BIT & 0xf];
                // 取每一个字节的高四位换成16进制字母
                str[2 * i + 1] = hexChar[b & 0xf];
            }
            output = new String(str);
        } catch (Exception e) {
            log.error("md5加密异常：", e);
        }

        return output;
    }
}
